package com.devin.dao;

import com.devin.pojo.Permission;
import com.devin.pojo.Role;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.type.JdbcType;

import java.util.List;

public interface RoleMapper {
    @Select("select * from role where id in(select roleId from users_role where userId=#{id})")
    @Results({@Result(id = true,property = "id",column = "id",jdbcType = JdbcType.INTEGER),
            @Result(property = "roleName",column = "roleName",jdbcType = JdbcType.VARCHAR),
            @Result(property = "roleDesc",column = "roleDesc",jdbcType = JdbcType.VARCHAR)
    })
    List<Role> getRolesById(int id);

    @Select(" select * from role ")
    List<Role> getRoles();


    @Select("select * from role ")
    @Results({@Result(id = true,property = "id",column = "id",jdbcType = JdbcType.INTEGER),
            @Result(property = "roleName",column = "roleName",jdbcType = JdbcType.VARCHAR),
            @Result(property = "roleDesc",column = "roleDesc",jdbcType = JdbcType.VARCHAR),
            @Result(property = "permissions",column = "id",
                    javaType = List.class,
                    many = @Many(select = "com.devin.dao.PermissionMapper.getPermissionsById")
            )
    })
    List<Role> getRolesAll();

    @Insert(" insert into role values(null,#{roleName,jdbcType=VARCHAR},#{roleDesc,jdbcType=VARCHAR})")
    @Options(useGeneratedKeys = true,keyColumn = "id",keyProperty = "id")
    void addRole(Role role);

    @Insert(" insert into role_permission values(#{permissionId,jdbcType=INTEGER},#{roleId,jdbcType=INTEGER})")
    void addRoleAndPermission(@Param("roleId") int roleId,@Param("permissionId") int permissionId);

    @Update(" delete from role_permission where roleId=#{roleId}")
    void delRoleAndPermission(int roleId);

    @Update(" delete from role where id=#{roleId}")
    void delRole(int roleId);

    @Select(" select * from role where id=#{roleId}")
    @Results({@Result(id = true,property = "id",column = "id"),
            @Result(property = "roleName",column = "roleName",jdbcType = JdbcType.VARCHAR),
            @Result(property = "roleDesc",column = "roleDesc",jdbcType = JdbcType.VARCHAR),
            @Result(property = "permissions",column = "id",javaType = List.class,
                    many = @Many(select ="com.devin.dao.PermissionMapper.getPermissionsById" ))

    })
    Role getRoleById(int roleId);

    @Update(" delete from role_permission where permissionId=#{permissionId} and roleId=#{roleId}")
    void delPermissionByRoleId(@Param("roleId") Integer roleId, @Param("permissionId") Integer permissionId);

    @Select(" select * from role where id not in(select roleId from users_role where userId=#{userId})")
    List<Role> getRoles2Json(Integer userId);

}
